package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutContract;
import com.lkd.contract.VendoutResultContract;
import com.lkd.dao.VendoutRunningDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.SkuEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.ChannelService;
import com.lkd.service.SkuService;
import com.lkd.service.VendoutRunningService;
import com.lkd.vo.Pager;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class VendoutRunningServiceImpl extends ServiceImpl<VendoutRunningDao, VendoutRunningEntity> implements VendoutRunningService {

    @Autowired
    private ChannelService channelService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private MqttProducer mqttProducer;



    @Override
    public Pager<VendoutRunningEntity> findPage(long pageIndex, long pageSize, Map searchMap) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<VendoutRunningEntity> page =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageIndex, pageSize);

        QueryWrapper queryWrapper = createQueryWrapper(searchMap);
        this.page(page, queryWrapper);

        Pager<VendoutRunningEntity> pageResult = new Pager<>();
        pageResult.setCurrentPageRecords(page.getRecords());
        pageResult.setPageIndex(page.getCurrent());
        pageResult.setPageSize(page.getSize());
        pageResult.setTotalCount(page.getTotal());
        return pageResult;
    }

    /**
     * 处理出货流水
     *
     * @param vendoutContract
     */
    @Override
    public void vendout(VendoutContract vendoutContract) {
        //1.扣减库存
        updateStore(vendoutContract.getInnerCode(), vendoutContract.getVendoutData().getSkuId(), vendoutContract.getVendoutData().getChannelCode(),true);

        //2.记录出货流水
        VendoutRunningEntity vendoutRunningEntity = new VendoutRunningEntity();
        vendoutRunningEntity.setInnerCode(vendoutContract.getInnerCode());
        vendoutRunningEntity.setOrderNo(vendoutContract.getVendoutData().getOrderNo());
        //查询商品信息
        SkuEntity skuEntity = skuService.getById(vendoutContract.getVendoutData().getSkuId());
        if (skuEntity == null) {
            return;
        }
        vendoutRunningEntity.setSkuId(vendoutContract.getVendoutData().getSkuId());
        vendoutRunningEntity.setSkuName(skuEntity.getSkuName());
        vendoutRunningEntity.setStatus(VMSystem.ORDER_STATUS_VENDOUT_FAIL);
        this.save(vendoutRunningEntity);


        //3.发送消息到售货机
        try {
            mqttProducer.send(TopicConfig.getVendoutTopic(vendoutContract.getInnerCode()), 2, vendoutContract);
        } catch (JsonProcessingException e) {
            log.error("发送出货消息失败" + e.getMessage());
        }

    }

    /**
     * 更改库存
     * @param innerCode
     * @param skuId
     * @param channelCode
     * @param operation
     */
    private void updateStore(String innerCode, Long skuId, String channelCode, Boolean operation) {
        ChannelEntity channelEntity = channelService.getOne(Wrappers.<ChannelEntity>lambdaQuery()
                .eq(ChannelEntity::getInnerCode, innerCode)
                .eq(ChannelEntity::getSkuId, skuId)
                .eq(ChannelEntity::getChannelCode, channelCode));
        if (channelEntity == null || channelEntity.getCurrentCapacity() < 1) {
            throw new LogicException("库存不足");
        }
        if (operation) {
            channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity() - 1);
        }else {
            channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity() + 1);
        }
        channelService.updateById(channelEntity);
    }

    /**
     * 售货机出货成功
     */
    @Override
    public void vendoutSuccess(VendoutResultContract resultContract) {
        //修改出货流水状态
        //查询订单
        LambdaQueryWrapper<VendoutRunningEntity> wrapper = new LambdaQueryWrapper<>();
        if (resultContract.getVendoutData().getOrderNo() != null) {
            wrapper.eq(VendoutRunningEntity::getOrderNo, resultContract.getVendoutData().getOrderNo());
        }
        if (StringUtils.isNotBlank(resultContract.getInnerCode())) {
            wrapper.eq(VendoutRunningEntity::getInnerCode, resultContract.getInnerCode());
        }

        VendoutRunningEntity vendoutRunningEntity = this.getOne(wrapper);
        vendoutRunningEntity.setStatus(VMSystem.ORDER_STATUS_VENDOUT_SUCCESS);

        this.updateById(vendoutRunningEntity);
    }

    /**
     * 售货机出货失败
     *
     * @param resultContract
     */
    @Override
    public void vendoutFail(VendoutResultContract resultContract) {
        //回滚库存
        updateStore(resultContract.getInnerCode(),resultContract.getVendoutData().getSkuId(), resultContract.getVendoutData().getChannelCode(),false);
    }

    @Override
    public List<VendoutRunningEntity> findList(Map searchMap) {
        QueryWrapper queryWrapper = createQueryWrapper(searchMap);
        return this.list(queryWrapper);
    }

    /**
     * 条件构建
     *
     * @param searchMap
     * @return
     */
    private QueryWrapper createQueryWrapper(Map searchMap) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (searchMap != null) {
            queryWrapper.allEq(searchMap);
        }
        return queryWrapper;
    }

}
